// 
// Copyright (c) 2006-2009 Ben Motmans
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Author(s):
//    Ben Motmans <ben.motmans@gmail.com>
//

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace Anculus.Core
{
	internal static class Crypto
	{
		internal static MemoryStream Transform (ByteBuffer source, ICryptoTransform transform)
		{
			MemoryStream dest = new MemoryStream (source.Length);
			using (CryptoStream cs = new CryptoStream (dest, transform, CryptoStreamMode.Write)) {
				cs.Write (source.Raw, 0, source.Length);
			}
			return dest;
		}
		
		internal static void TransformFile (string source, string dest, ICryptoTransform transform)
		{
			using (FileStream fss = File.Open (source, FileMode.Open, FileAccess.Read)) {
				using (FileStream fsd = File.OpenWrite (dest)) {
					using (CryptoStream cs = new CryptoStream (fsd, transform, CryptoStreamMode.Write)) {
						byte[] buffer = new byte[4096];
						
						int read = fss.Read (buffer, 0, 4096);
						while (read > 0) {
							cs.Write (buffer, 0, read);
							read = fss.Read (buffer, 0, 4096);
						}
					}
				}
			}
		}
		
		internal static ByteBuffer CopyDataToSize (ByteBuffer source, int len)
		{
			if (len < 1)
				throw new ArgumentException ("len must be > 0.");
			if (source == null || source.Length == 0)
				throw new ArgumentException ("source");

			byte[] data = new byte[len];
			if (source.Length >= len) {
				//more data then we need, so simply copy
				Array.Copy (source.Raw, 0, data, 0, len);
			} else {
				//not enough, copy multiple times
				int sourcelen = source.Length;
				int need = len;
				while (need > 0) {
					Array.Copy (source.Raw, 0, data, len - need, sourcelen > need ? need : sourcelen);
					need -= sourcelen;
				}
			}
			
			return new ByteBuffer (data);
		}
	}
}